package com.cm386.final_project_timezonealert;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.cm386.final_project_timezonealert.dao.DBService;
import com.cm386.final_project_timezonealert.model.City;
import com.cm386.final_project_timezonealert.model.Region;
import com.cm386.final_project_timezonealert.model.RegionService;
import com.cm386.final_project_timezonealert.view.RegionListItems;

public class RegionActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_region);
		List<Region> regions    			  = RegionService.getRegions(); 
		List<RegionListItems> regionListItems = new ArrayList<RegionListItems>();
		for (Region region : regions)
			regionListItems.add(new RegionListItems(region.getName()));
		int[] to   	  = new int[] {R.id.regionTextView};
		String[] from = new String[] {RegionListItems.REGION_NAME_KEY}; 
		SimpleAdapter adapter = new SimpleAdapter(this, regionListItems, R.layout.region_item, from, to);
		
		ListView regionListView = (ListView) this.findViewById(R.id.regionListView);
		regionListView.setAdapter(adapter);
		
		regionListView.setOnItemClickListener(new OnItemClickListener() {
			List<Region> regions;
			public OnItemClickListener init(List<Region> regions){
				this.regions = regions;
				return this;
			}
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				Region region 	 	   = regions.get(position);
				List<City> selectedCitiesItemsByRegion = DBService.getInstance(RegionActivity.this).fetchCityByRegion(region);
				ArrayList<City> cities = new ArrayList<City>(region.getCities());
				for (City selectedCity : selectedCitiesItemsByRegion){
					for (int i=0; i<cities.size(); i++){
						if (selectedCity.getTimeZoneId().equalsIgnoreCase(cities.get(i).getTimeZoneId())){
							cities.remove(i);
							continue;
						}	
					}
				}
				if (cities != null){
					Intent cityActivity = new Intent();
					cityActivity.setClass(RegionActivity.this, CityActivity.class);
					cityActivity.putExtra("CityList", cities);
					startActivity(cityActivity);
				}
			}
		}.init(regions));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.region, menu);
		return true;
	}

}
